package com.fh.constants;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

public class Configs {

	public static void main(String[] args) {
		System.out.println(Configs.getConfig("oss.image.process.url"));
	}

	private static String config_property = "/config.properties";

	private static Properties p;

	public static Map<String, Object> configs = new HashMap<String, Object>();

	static {
		// properties 文件读取
		InputStream is = Configs.class.getResourceAsStream(config_property);
		p = new Properties();
		try {
			p.load(is);
			for (Entry<Object, Object> entry : p.entrySet()) {
				String valur = entry.getValue().toString().trim();
				String key = entry.getKey().toString().trim();
				int i = 0;
				while (true) {
					if (valur.startsWith("string:")) {
						valur = valur.substring(valur.indexOf(":") + 1);
						configs.put(key, valur);
						break;
					}

					try {
						switch (i) {
						case 0:
							configs.put(key, Long.valueOf(valur));
							break;
						case 1:
							configs.put(key, Double.valueOf(valur));
							break;
						case 2:
							configs.put(key, valur);
							break;
						default:
							break;
						}
						break;
					} catch (Exception e) {
						continue;
					} finally {
						i++;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 对特别字段进行替换处理
		for (Iterator<String> it = configs.keySet().iterator(); it.hasNext();) {
			String key = it.next();
			Object v = configs.get(key);
			if (!(v instanceof String)) {
				continue;
			}
			String str = v.toString().trim();
			int index = -1;
			while ((index = str.indexOf("{", index + 1)) != -1) {
				int tmp = str.indexOf("}", index);
				if (tmp == -1) {
					continue;
				}
				String var = str.substring(index + 1, tmp);

				if (var.matches("\\d+")) {
					continue;
				}
				if (configs.get(var) != null) {
					str = str.replace("{" + var + "}", configs.get(var).toString());
				}
			}
			configs.put(key, str);
		}
	}

	/**
	 * 获取配置项的值
	 */
	public static String getConfig(String key) {
		return configs.get(key).toString();
	}
}
